import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;

public class TCPPortScannerTest {
	
	static void usage() {
        System.out.println("Usage:\njava TCPPortScanner host [startport] [endport]");           
        System.out.println("If only startport is specified, the portscanner scans only that port.");
        System.out.println("If neither is specified, the portscanner scans all ports from 1-65535");
        
        System.exit(0);
    }
    
	
	public static void main(String [] args) {
		TCPPortScanner portScanner = null;
		InetAddress host = null;
		int startPort = 0, endPort = 1024;
			
		try {
			switch(args.length) {
			case 0:
				usage();
			case 1:
				try {
					host = InetAddress.getByName(args[0]);
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				break;
			case 2:
				try {
					host = InetAddress.getByName(args[0]);
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				endPort = Integer.parseInt(args[1]);
				if(endPort > 65535 || endPort < 0)
					throw new NumberFormatException();
				break;
			case 3:
				try {
					host = InetAddress.getByName(args[0]);
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				
				startPort = Integer.parseInt(args[1]);
				endPort = Integer.parseInt(args[2]);
				if(startPort > 65535 || endPort > 65535 || startPort < 0 || endPort < 0)
					throw new NumberFormatException();
				break;
			default:
				throw new NumberFormatException();
			}
		} catch(NumberFormatException e) {
			System.out.println("Startport & endport must be smaller than 65536\n" + e);
		}
		
		portScanner = new TCPPortScanner(host, startPort, endPort);
		
		// Run the port detection on the selected host
		portScanner.runPortScanning();		
		
		// Printing all the ports that are open (if any)
		ArrayList<Integer> ports = new ArrayList<Integer>();
		
		for(int i = startPort; i < endPort; i++) {
			if(OpenPorts.getInstance().get(i))
				ports.add(i);
		}
		if(!ports.isEmpty()) {
			System.out.println("Open ports are: ");
			Iterator<Integer> itr = ports.iterator();
			while (itr.hasNext()) {
				boolean ftp = false;
				boolean http = false;
				Integer port = itr.next();
				System.out.println("\n" + "Discover service for port "+port);
				DiscoverServices dS = new DiscoverServices(port, host);
				
				if(dS.discoverFTP()){
					System.out.println("FTP is currently working");
					ftp = true;
				} else System.out.println("FTP is not working");
				if(dS.discoverHTTP()){
					System.out.println("HTTP is currently working");
					http = true;
				} else System.out.println("HTTP is not working");
				
				if(!ftp && !http){
					dS.discoverWithList();
				}
			}
		} else {
			System.out.println("No ports are open on this host.");
		}
	}
}
